package com.gingko.duominuo.ui.fragment

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.gingko.duominuo.data.Resource
import com.gingko.duominuo.data.model.JobReviewContentVo
import com.gingko.duominuo.data.model.ReviewTaskVo
import com.gingko.duominuo.data.model.WorkOrderItemVo
import com.gingko.duominuo.data.model.WorkOrderVo
import com.gingko.duominuo.databinding.FragmentWorkOrderBinding
import com.gingko.duominuo.ui.activity.ReviewWorkOrderActivity
import com.gingko.duominuo.ui.adapter.WorkOrderAdapter
import com.gingko.duominuo.ui.widget.DefaultItemDecoration
import com.gingko.duominuo.ui.widget.EmptyLayout
import com.gingko.duominuo.utils.NameMappingUtils
import com.gingko.duominuo.utils.singleClick
import com.gingko.duominuo.utils.toFriendlyTime
import com.gingko.duominuo.utils.toast
import com.gingko.duominuo.viewmodel.BaseViewModel
import com.gingko.duominuo.viewmodel.WorkOrderViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class WorkOrderFragment : BaseFragment() {
    private val mViewBinding: FragmentWorkOrderBinding by lazy {
        FragmentWorkOrderBinding.inflate(
            layoutInflater
        )
    }
    private val mViewModel by viewModels<WorkOrderViewModel>()
    private val workOrderDetailVos by lazy { mutableListOf<WorkOrderItemVo>() }
    private val workOrderAdapter by lazy { WorkOrderAdapter(requireContext(), workOrderDetailVos) }
    private var jobReviewContentVo: JobReviewContentVo? = null
    private var workOrderVo: WorkOrderVo? = null
    private var orderId: String? = null
    private var isFirstLoad = true
    private var isFromReviewBack = false

    companion object {
        const val REQ_REVIEW_CODE = 1

        @JvmStatic
        fun newInstance() = WorkOrderFragment()
    }

    override fun getContentView(inflater: LayoutInflater, container: ViewGroup?): View {
        return mViewBinding.root
    }

    override fun getViewModel(): BaseViewModel {
        return mViewModel
    }

    override fun onResume() {
        super.onResume()
        if (!isFirstLoad && isVisible) {
            if (isFromReviewBack) {
                workOrderVo?.created_at?.let { mViewModel.startTaskCountdown(it) }
                mViewModel.loadReviewTaskFromDB(orderId!!)
                isFromReviewBack = false
            } else {
                mViewModel.getUnFinishWorkOrder(isFirstLoad)
            }
        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        if (!hidden && !isFirstLoad) {
            mViewModel.getUnFinishWorkOrder(isFirstLoad)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initView(view: View, savedInstanceState: Bundle?) {
        mViewModel.getInterceptAndInject()
        mViewBinding.titleView.setOnMenuItemClickListener {
            val data = jobReviewContentVo?.specification ?: arrayListOf()
            if (data.isEmpty()) {
                "无审核条件信息".toast()
                return@setOnMenuItemClickListener true
            }
            ReviewConditionsFragment.newInstance(data)
                .showNow(childFragmentManager, "reviewConditionFragment")
            true
        }
        mViewBinding.rcvWorkOrder.addItemDecoration(
            DefaultItemDecoration(
                requireContext(),
                LinearLayoutManager.VERTICAL,
                1
            )
        )
        workOrderAdapter.callback = object : WorkOrderAdapter.Callback {
            override fun onClickItem(position: Int) {
                val reviewTaskVO =
                    ReviewTaskVo(orderId, position, workOrderDetailVos, jobReviewContentVo)
                val injectAndInterceptVo =
                    mViewModel.getInjectAndInterceptByPlatform(jobReviewContentVo?.app)
                val intent = ReviewWorkOrderActivity.getStartIntent(
                    requireContext(),
                    reviewTaskVO,
                    injectAndInterceptVo
                )
                startActivityForResult(intent, REQ_REVIEW_CODE)
            }
        }
        mViewBinding.rcvWorkOrder.adapter = workOrderAdapter
        mViewBinding.refreshLayout.setOnRefreshListener {
            mViewModel.getUnFinishWorkOrder(true)
        }
        mViewBinding.refreshLayout.autoRefresh()
        mViewBinding.tvSubmitTask.singleClick(2000) {
            mViewModel.submitTask(orderId!!)
        }
        observerData()
    }

    @SuppressLint("SetTextI18n")
    private fun observerData() {
        mViewModel.workOrderLiveData.observe(owner = this) {
            mViewBinding.refreshLayout.closeHeaderOrFooter()
            when (it) {
                is Resource.Success -> {
                    isFirstLoad = false
                    if (it.data == null) {
                        mViewBinding.emptyLayout.show(EmptyLayout.NO_DATA)
                    } else {
                        initTaskData(it.data)
                        mViewBinding.emptyLayout.hide()
                    }
                }
                is Resource.Error -> {
                    mViewBinding.emptyLayout.show(EmptyLayout.LOAD_ERROR)
                    it.throwable?.message?.toast()
                }
            }
        }
        mViewModel.workOrderDetailLiveData.observe(owner = this) { resource ->
            workOrderDetailVos.clear()
            when (resource) {
                is Resource.Success -> {
                    if (!resource.data?.data.isNullOrEmpty()) {
                        workOrderDetailVos.addAll(resource.data?.data ?: listOf())
                    }
                    val reviewCount = workOrderDetailVos.filter { it.reviewStatus == true }.size
                    mViewBinding.tvTaskReviewNumber.text = reviewCount.toString()
                    mViewBinding.tvTaskTotalNumber.text = "/${workOrderDetailVos.size}"
                    mViewBinding.tvSubmitTask.isEnabled =
                        reviewCount == workOrderDetailVos.size && mViewModel.countdownLiveData.value != 0L
                }
                is Resource.Error -> {
                    resource.throwable?.message?.toast()
                }
            }
            workOrderAdapter.notifyDataSetChanged()
        }

        mViewModel.jobReviewContentLiveData.observe(owner = this) {
            jobReviewContentVo = it.data
        }
        mViewModel.countdownLiveData.observe(owner = this) { time ->
            mViewBinding.tvEndDate.text = time.toFriendlyTime()
            val isAllOperate =
                workOrderDetailVos.filter { it.reviewStatus == true }.size == workOrderDetailVos.size
            mViewBinding.tvSubmitTask.isEnabled = time != 0L && isAllOperate
            if (time == 0L) {
                mViewModel.getUnFinishWorkOrder(false)
            }
        }
        mViewModel.submitTaskLiveData.observe(owner = this) {
            when (it) {
                is Resource.Success -> {
                    "提交成功".toast()
                    mViewModel.getUnFinishWorkOrder(true)
                }
                is Resource.Error -> it.throwable?.message?.toast()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQ_REVIEW_CODE) {
            isFromReviewBack = true
        }
    }

    private fun initTaskData(workOrderVo: WorkOrderVo) {
        orderId = workOrderVo.id
        this.workOrderVo = workOrderVo
        workOrderVo.created_at?.let { mViewModel.startTaskCountdown(it) }
        mViewBinding.tvTaskProject.text = NameMappingUtils.getProjectName(workOrderVo.proj) ?: "--"
        mViewBinding.tvTaskType.text = NameMappingUtils.getTaskName(workOrderVo.task) ?: "--"
        mViewBinding.tvTaskPlatform.text = NameMappingUtils.getPlatformName(workOrderVo.app) ?: "--"
    }
}